package com.angel.data.generator.preProcess.impl;

import javax.persistence.Table;

import org.apache.log4j.Logger;

import com.angel.dao.generic.jdbc.info.JDBCConnectionInfo;
import com.angel.dao.generic.jdbc.pooling.JDBCPoolingDriver;
import com.angel.data.generator.base.DataClassGenerator;
import com.angel.data.generator.exceptions.DataGeneratorException;
import com.angel.data.generator.preProcess.PreProcessStrategy;

/**
 *
 * @author William
 *
 */
public class JDBCDropPreProcessStrategy implements PreProcessStrategy{

    private static final long serialVersionUID = 2940890328072901046L;

    private static final Logger LOGGER = Logger.getLogger(JDBCDropPreProcessStrategy.class);

    private JDBCPoolingDriver jdbcPoolingDriver;

    public JDBCDropPreProcessStrategy(JDBCPoolingDriver jdbcPoolingDriver){
        super();
        this.jdbcPoolingDriver = jdbcPoolingDriver;
    }

    public JDBCDropPreProcessStrategy(JDBCConnectionInfo jdbcConnectionInfo){
        super();
        this.jdbcPoolingDriver = new JDBCPoolingDriver(jdbcConnectionInfo);
    }

    public void preProcess(DataClassGenerator dataClassGenerator) {
        Class<? extends Object> domainObjectClass = dataClassGenerator.getDataGenerator().getDataGeneratorClass();
        String tableName = domainObjectClass.getAnnotation(Table.class) != null ?
        		domainObjectClass.getAnnotation(Table.class).name() : domainObjectClass.getSimpleName();

        boolean existTable = jdbcPoolingDriver.existTable(tableName);

        if(existTable){
        	LOGGER.info("Table [" +tableName + "] exists for domain object [" + domainObjectClass.getSimpleName() + "].");

        	jdbcPoolingDriver.executeDisableTableContraints(tableName);

            jdbcPoolingDriver.executeDropTable(tableName);

        } else {
        	LOGGER.info("Table [" +tableName + "] doesn't exist for domain object [" + domainObjectClass.getSimpleName() + "].");
        }
    }

    /**
     * @return the jdbcPoolingDriver
     */
    public JDBCPoolingDriver getJdbcPoolingDriver() {
        return jdbcPoolingDriver;
    }


    /**
     * @param jdbcPoolingDriver the jdbcPoolingDriver to set
     */
    public void setJdbcPoolingDriver(JDBCPoolingDriver jdbcPoolingDriver) {
        this.jdbcPoolingDriver = jdbcPoolingDriver;
    }

	public String getName() {
		return "JDBCDropTablePreProcess";
	}

	public void finalizePreProcess() {
		try {
			this.getJdbcPoolingDriver().finalizeConnection();
		} catch(Exception e){
			throw new DataGeneratorException(e);
		}
	}

	public void initializePreProcess() {
		try{
			this.getJdbcPoolingDriver().initializeConnection();
		} catch(Exception e){
			throw new DataGeneratorException(e);
		}
	}
}
